package com.dsz.Util;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class DatabaseDelete {

    private static final String JDBC_URL_PREFIX = "jdbc:mysql://localhost:3306/";
    // 单例模式，确保只有一个数据库连接实例
    private static String URL;
    private static String DELETE_SQL;
    private static final String USER = "root";
    private static final String PASSWORD = "root";
    private static Connection connection;
    static {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入数据库名称: ");
        String databaseName = scanner.nextLine();
        System.out.print("请输入表名称: ");
        String tableName = scanner.nextLine();
        URL = JDBC_URL_PREFIX + databaseName;
        DELETE_SQL = "DELETE FROM " + tableName;
        scanner.close();
    }
    // 私有构造函数，防止外部实例化
    /**
     * 获取数据库连接
     * @return 数据库连接对象
     * @throws SQLException 如果连接失败
     */
    public static Connection getConnection() throws SQLException {
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
        }
        return connection;
    }
    /**
     * 关闭数据库连接
     */
    public static void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    public static void deleteFromDataBaseTable() {
        //调用数据库的操作
        try (
                Connection connection = DatabaseDelete.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(DELETE_SQL)) {

            int rowinserted = preparedStatement.executeUpdate();
            if (rowinserted > 0) {
                System.out.println("删除表数据成功");
            } else {
                System.out.println("删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        deleteFromDataBaseTable();
    }





}
